Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

  1. "1 + 1" = 2
  2. " 2-1 + 2 " = 3
  3. "(1+(4+5+2)-3)+(6+8)" = 23
  4. `

Note: Do not use the eval built-in library function.

Solution:

  1. public class Solution {
  2. public int calculate(String s) {
  3. char[] a = s.toCharArray();
  4. Stack<Integer> stack = new Stack<Integer>();
  5. stack.push(1);
  6. int res = 0;
  7. int sign = 1;
  8. for (int i = 0; i < a.length; i++) {
  9. if (a[i] == ')') {
  10. stack.pop();
  11. } else if (a[i] == '+') {
  12. sign = 1;
  13. } else if (a[i] == '-') {
  14. sign = -1;
  15. } else if (a[i] == '(') {
  16. stack.push(stack.peek() * sign);
  17. sign = 1;
  18. } else if (Character.isDigit(a[i])) {
  19. int tmp = a[i] - '0';
  20. while (i + 1 < s.length() && Character.isDigit(a[i + 1]))
  21. tmp = tmp * 10 + a[++i] - '0';
  22. res += sign * stack.peek() * tmp;
  23. }
  24. }
  25. return res;
  26. }
  27. }